#include "flowmeter.h"
#include <QDebug>

//读取流量计串口数据
QString Flowmeter::getReadCmd(QString protocol,int commAddr)
{
    QByteArray ba=protocol.toLatin1();
    const char *protocol_char=ba.data();
    QMetaEnum metaEnum=QMetaEnum::fromType<protocolList>();
    protocolList proInt=protocolList(metaEnum.keyToValue(protocol_char));
    QString addrStr;
    addrStr.sprintf("%02X",commAddr);
    QString crcStr;
    //crcStr=sprintf("%02X",(addrStr.at(0).toLatin1()+addrStr.at(1)+'R'+'D')%255);

    QString cmdStr="";

    switch (proInt) {
    case A:

    case B:

    case C:

    case D:

    default:
        cmdStr="@"+addrStr+"RD";
        crcStr.sprintf("%02X",getCrc(cmdStr,1,4));
        cmdStr+=crcStr+"\r";
        break;
    }
    //qDebug()<<proInt;
    return cmdStr;//tprotocol;//cmdStr;
}



QString Flowmeter::getDataResultStr(QString protocol,int commAddr,QString recvData)
{
    QByteArray ba=protocol.toLatin1();
    const char *protocol_char=ba.data();
    QMetaEnum metaEnum=QMetaEnum::fromType<protocolList>();
    protocolList proInt=protocolList(metaEnum.keyToValue(protocol_char));
    QString pvStr;
    QString svStr;
    QString ResultStr="";

    QString addrStr;
    addrStr.sprintf("%02X",commAddr);
    if(recvData.size()<24) {ResultStr="length Error:"+recvData; return ResultStr;}
    if(!recvData.startsWith("@"+addrStr+"RD")) {ResultStr="@XXRD Error:"+recvData; return ResultStr;}

    QString crcStr="00";
    //crcStr=sprintf("%02X",(addrStr.at(0).toLatin1()+addrStr.at(1)+'R'+'D')%255);



    switch (proInt) {
    case A:
        crcStr.sprintf("%02X",getCrc(recvData,1,21)+2);
        break;
    case B:
        crcStr.sprintf("%02X",getCrc(recvData,1,21));
        break;
    case C:
        crcStr.sprintf("%02X",getCrc(recvData,0,22));
        break;
    case D:
        crcStr.sprintf("%02X",getCrc(recvData,5,17));
        break;
    default:
            ResultStr="Not Process:"+recvData;
        break;
    }

    pvStr.sprintf("%.2f",recvData.mid(5,6).toFloat()/100);
    svStr.sprintf("%d",recvData.mid(11,11).toInt());


    //qDebug()<<crcStr;
    if(!recvData.endsWith(crcStr+"\r")) {ResultStr="Crc or \\r Error:"+recvData; return ResultStr;}
    //qDebug()<<proInt;
    ResultStr="瞬时流量:"+pvStr+" m3/h, 累积流量:"+svStr+" 吨(m3)";
    return ResultStr;//tprotocol;//cmdStr;
}




int Flowmeter::getCrc(const QString Str,int startIndex,int length)
{
    int crcValue=0;
    int endIndex=0;
    //if(startIndex>Str.length()) return -1;
    if((startIndex+length)>Str.length()) return -1;
    endIndex=startIndex+length;
    QByteArray Byte=Str.toUtf8();
    for(int i=startIndex;i<endIndex;i++)
    {
        crcValue^=int(Byte.at(i));
        //qDebug()<<Byte.at(i)<<"-"<<int(Byte.at(i));
    }

    return (crcValue)%256;
}
